const express = require('express');
const mongoose = require('mongoose');
const http = require('http');
const { Server } = require('socket.io');
const cors = require('cors');

// 创建Express应用
const app = express();
app.use(cors());
app.use(express.json());

// 创建HTTP服务器并集成Socket.io
const server = http.createServer(app);
const io = new Server(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});

// 连接MongoDB数据库
// 注意：在mongoose 6.0+中，useNewUrlParser和useUnifiedTopology默认已启用
mongoose.connect('mongodb://localhost:27017/smartHomeSystem')
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('MongoDB connection error:', err));

// 定义家庭成员模型
const FamilyMemberSchema = new mongoose.Schema({
  name: { type: String, required: true },
  id: { type: String, required: true, unique: true },
  role: { type: String, required: true }
});

const FamilyMember = mongoose.model('FamilyMember', FamilyMemberSchema);

// 定义设备状态模型
const DeviceStatusSchema = new mongoose.Schema({
  deviceType: { type: String, required: true },
  deviceId: { type: String, required: true, unique: true },
  status: { type: Object, required: true },
  lastUpdated: { type: Date, default: Date.now }
});

const DeviceStatus = mongoose.model('DeviceStatus', DeviceStatusSchema);

// 定义天气数据模型
const WeatherSchema = new mongoose.Schema({
  date: { type: Date, required: true, unique: true },
  temperature: { type: Number, required: true },
  humidity: { type: Number, required: true },
  condition: { type: String, required: true },
  location: { type: String, required: true }
});

const Weather = mongoose.model('Weather', WeatherSchema);

// API路由
app.get('/', (req, res) => {
  res.send('Smart Home System API is running');
});

// 家庭成员相关路由
app.post('/api/family-members', async (req, res) => {
  try {
    const member = new FamilyMember(req.body);
    await member.save();
    res.status(201).json(member);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

app.get('/api/family-members', async (req, res) => {
  try {
    const members = await FamilyMember.find();
    res.json(members);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.get('/api/family-members/:id', async (req, res) => {
  try {
    const member = await FamilyMember.findById(req.params.id);
    if (!member) return res.status(404).json({ error: 'Member not found' });
    res.json(member);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 设备状态相关路由
app.post('/api/device-status', async (req, res) => {
  try {
    const status = new DeviceStatus(req.body);
    await status.save();
    res.status(201).json(status);
    // 通过WebSocket通知前端设备状态更新
    io.emit('deviceStatusUpdate', status);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

app.get('/api/device-status', async (req, res) => {
  try {
    const statuses = await DeviceStatus.find();
    res.json(statuses);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 天气相关路由
app.post('/api/weather', async (req, res) => {
  try {
    const weather = new Weather(req.body);
    await weather.save();
    res.status(201).json(weather);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

app.get('/api/weather/tomorrow', async (req, res) => {
  try {
    // 获取明天的日期
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    tomorrow.setHours(0, 0, 0, 0);

    // 查找明天的天气数据
    const weather = await Weather.findOne({
      date: {
        $gte: tomorrow,
        $lt: new Date(tomorrow.getTime() + 24 * 60 * 60 * 1000)
      }
    });

    if (!weather) return res.status(404).json({ error: 'Weather data not found' });
    res.json(weather);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// WebSocket连接处理
io.on('connection', (socket) => {
  console.log('A user connected');

  // 处理空调控制命令
  socket.on('controlAC', async (data) => {
    try {
      // 更新数据库中的空调状态
      let acStatus = await DeviceStatus.findOneAndUpdate(
        { deviceType: 'airConditioner', deviceId: data.deviceId },
        { status: data.status, lastUpdated: Date.now() },
        { new: true, upsert: true }
      );

      // 广播空调状态更新
      io.emit('acStatusUpdated', acStatus);
    } catch (error) {
      console.error('Error updating AC status:', error);
    }
  });

  // 处理厨房设备监控
  socket.on('kitchenMonitor', async (data) => {
    try {
      // 更新数据库中的厨房设备状态
      let kitchenStatus = await DeviceStatus.findOneAndUpdate(
        { deviceType: 'kitchenDevice', deviceId: data.deviceId },
        { status: data.status, lastUpdated: Date.now() },
        { new: true, upsert: true }
      );

      // 广播厨房设备状态更新
      io.emit('kitchenStatusUpdated', kitchenStatus);
    } catch (error) {
      console.error('Error updating kitchen device status:', error);
    }
  });

  socket.on('disconnect', () => {
    console.log('User disconnected');
  });
});

// 启动服务器
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});